<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>节奏文件管理</span>
          <div class="back-button">
            <el-button @click="goBack">返回列表</el-button>
          </div>
        </div>
      </template>

      <el-descriptions title="节奏型信息" :column="2" border>
        <el-descriptions-item label="节奏型名称">{{ patternInfo.patternName }}</el-descriptions-item>
        <el-descriptions-item label="律动类型">{{ patternInfo.rhythm }}</el-descriptions-item>
        <el-descriptions-item label="节拍">{{ patternInfo.beat }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">节奏文件列表</el-divider>

      <el-table v-loading="loading" :data="fileList" style="width: 100%">
        <el-table-column label="调式" prop="mode" />
        <el-table-column label="级数" prop="audioLevel" />
        <el-table-column label="和弦音频1" width="350">
          <template #default="scope">
            <a v-if="scope.row.vurl1" :href="scope.row.vurl1" target="_blank">点击播放</a>
            <div v-else>暂无上传</div>
          </template>
        </el-table-column>
        <el-table-column label="和弦音频2" width="350">
          <template #default="scope">
            <a v-if="scope.row.vurl2" :href="scope.row.vurl2" target="_blank">点击播放</a>
            <div v-else>暂无上传</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <!-- <el-button link type="primary" @click="handleDownload(scope.row)">下载</el-button>
            <el-button link type="danger" @click="handleDeleteFile(scope.row)">删除</el-button> -->
            <el-button type="primary" @click="openUploadDialog(scope.row)">上传节奏文件</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 上传文件弹窗 -->
    <el-dialog title="上传节奏文件" v-model="uploadDialogVisible" width="500px" append-to-body>
      <!-- 显示当前行的调式和级数信息 -->
      <div class="row-info" v-if="currentRow">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="调式">{{ currentRow.mode }}</el-descriptions-item>
          <el-descriptions-item label="级数">{{ currentRow.audioLevel }}</el-descriptions-item>
        </el-descriptions>  
      </div>
      <el-divider content-position="center">上传音频1</el-divider>
      <AudioUpload v-model="uploadFiles1" />
      <el-divider content-position="center">上传音频2</el-divider>
      <AudioUpload v-model="uploadFiles2" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUpload">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PatternJieZou">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getPattern, getBPatternFile, uploadBPatternFile } from "@/api/system/pattern";
import AudioUpload from "@/components/AudioUpload/index.vue";

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 基础数据
const patternId = ref('');
const patternInfo = ref({});
const loading = ref(true);
const fileList = ref([]);

// 上传相关
const uploadDialogVisible = ref(false);
const uploadFiles1 = ref([]);
const uploadFiles2 = ref([]);
const currentRow = ref(null); // 当前选中的行数据

// 初始化数据
onMounted(() => {
  patternId.value = route.params.id;
  if (patternId.value) {
    getPatternInfo();
    getPatternFiles();
  } else {
    proxy.$modal.msgError("参数错误");
    goBack();
  }
});

// 获取节奏型信息
function getPatternInfo() {
  loading.value = true;
  getPattern(patternId.value).then(response => {
    patternInfo.value = response.data || {};
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 获取节奏文件列表
function getPatternFiles() {
  loading.value = true;
  getBPatternFile(patternId.value).then(response => {
    if (response.code === 200 && response.data) {
      fileList.value = response.data
    } else {
      fileList.value = [];
    }
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 打开上传弹窗
function openUploadDialog(row) {
  currentRow.value = row; // 保存当前行数据
  uploadDialogVisible.value = true;
  if (row.vurl1) {
    uploadFiles1.value = [{
      name: row.vurl1.split('/').pop(),
      url: row.vurl1,
      fileId: row.videoId1,
    }];
  } else {
    uploadFiles1.value = [];
  }
  if (row.vurl2) {
    uploadFiles2.value = [{
      name: row.vurl2.split('/').pop(),
      url: row.vurl2,
      fileId: row.videoId2,
    }];    
  }else {
    uploadFiles2.value = [];
  }
}

// 提交上传
function submitUpload() {
  
  if (!uploadFiles1.value.length) {
    proxy.$modal.msgError("请先选择要上传的音频文件1");
    return;
  }
  if (!uploadFiles2.value.length) {
    proxy.$modal.msgError("请先选择要上传的音频文件2");
    return;
  }
  if (!currentRow.value) {
    proxy.$modal.msgError("未选择上传目标行");
    return;
  }
  console.log("🚀 ~ submitUpload ~ formData:", uploadFiles1)
  const formData = {
    patternId: patternId.value,
    mode: currentRow.value.mode,
    audioLevel: currentRow.value.audioLevel,
    videoId1: uploadFiles1.value.map(file => file.fileId)[0],
    videoId2: uploadFiles2.value.map(file => file.fileId)[0],
  };
  
  uploadBPatternFile(formData).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("上传成功");
      uploadDialogVisible.value = false;
      getPatternFiles(); // 刷新文件列表
    } else {
      proxy.$modal.msgError(response.msg || "上传失败");
    }
  }).catch(() => {
    proxy.$modal.msgError("上传失败，请重试");
  });
}

// 下载文件
function handleDownload(row) {
  if (row.url) {
    window.open( row.url);
  }
}

// 删除文件
function handleDeleteFile(row) {
  proxy.$modal.confirm(`确定要删除文件 ${row.name} 吗？`).then(() => {
    // 这里应该调用删除文件的API，目前API中没有提供，需要后端支持
    // 暂时模拟删除成功
    proxy.$modal.msgSuccess("删除成功");
    fileList.value = fileList.value.filter(item => item.fileId !== row.fileId);
  }).catch(() => { });
}

// 返回列表页
function goBack() {
  router.back();
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-button {
  margin-left: auto;
}
</style>